/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.hibernate.utils;

import br.com.hibernate.entidades.Colaborador;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author ricardo
 */
public class MysqlHelper {
    
    public static Session getCurrentSession(){
        Session session = null;
        if(session == null || session.isOpen()){
            return session = SessionFactoryMysql.getCurrentSession();
        }else{
            return null;
        }
    }
    
    public static Object getObject(Class clazz, long id) {

        Session session = getCurrentSession();//sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();

        Object obj = null;
        try {
            obj = session.get(clazz, id);
            tx.commit();
            
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return obj;
    }
    
    public static Object getObject(Class clazz, String id) {

        Session session = getCurrentSession();//sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();

        Object obj = null;
        try {
            obj = session.get(clazz, id);
            tx.commit();
            
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }

        return obj;
    }
    
    public static Colaborador getColaborador(String strLogin, String strSenha){
        Session session = null;
        Transaction tx = null;
        Colaborador col = null;
        List result = null;
        if(strLogin.trim() != null && strSenha.trim() != null){
            try{
                session = getCurrentSession();
                Criteria criteria = session.createCriteria(Colaborador.class);
                criteria.add(Restrictions.eq("colStLogin", strLogin));
                criteria.add(Restrictions.eq("colStSenha", strSenha));
                criteria.add(Restrictions.eq("colBlAtivo", true));
                
                result = criteria.list();
            }finally{
                if (session != null && session.isOpen()) {
                    session.close();
                }
            }
        }
        if (result != null && result.size() > 0) {
            col =  (Colaborador) result.get(0);
        }
        return col;
    }
}
